package com.lin.mybatis.injector;

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

import java.lang.reflect.Field;
import java.util.List;

/**
 * @author: linjiang
 * @date: 2024/11/25
 * 功能：mybatis-plus的批量修改
 */
public class UpdateBatchById extends AbstractMethod {

    protected UpdateBatchById() {
        this("updateBatchById");
    }


    protected UpdateBatchById(String methodName) {
        super(methodName);
    }

    /**
     * 定义最初始的sql语句
     *
     * @param mapperClass mapper 接口
     * @param modelClass  mapper 泛型
     * @param tableInfo   数据库表反射信息
     * @return
     */
    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        String sqlScript = "<script>\nUPDATE %s %s \n</script>";
        String sqlFragment = preparedSqlFragment(tableInfo);
        String sql = String.format(sqlScript, tableInfo.getTableName(), sqlFragment);
        SqlSource sqlSource = super.createSqlSource(this.configuration, sql, modelClass);
        return this.addUpdateMappedStatement(mapperClass, modelClass, sqlSource);

    }

    /**
     * 准备sql片段
     *
     * @param tableInfo
     * @return
     */
    private String preparedSqlFragment(TableInfo tableInfo) {
        // 获取需要批量修改的字典
        List<TableFieldInfo> allFieldList = tableInfo.getFieldList();
        StringBuilder builder = new StringBuilder();
        builder.append("<trim prefix=\"SET\" suffixOverrides=\",\"> \n");
        for (TableFieldInfo tableFieldInfo : allFieldList) {
            Field field = tableFieldInfo.getField();
            String column = tableFieldInfo.getColumn();
            builder.append(column).append("=").append("CASE id\n")
                    .append("<foreach collection=\"list\" item=\"item\"> \n")
                    .append("WHEN ").append("#{").append("item.id").append("} ")
                    .append("THEN ").append("#{")
                    .append("item.").append(field.getName())
                    .append("} ")
                    .append("</foreach>")
                    .append("END").append(",");
        }

        builder.append("</trim>");
        builder.append("<where>");
        builder.append("id ").append("in");
        builder.append("<foreach collection=\"list\" item=\"item\" open=\"(\" close=\")\" separator=\",\"> \n");
        builder.append("#{").append("item.id").append("}");
        builder.append("</foreach>");
        builder.append("</where>");
        return builder.toString();
    }

}
